package com.chase.passwordmaster.main

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chase.passwordmaster.R
import com.chase.passwordmaster.add.AddActivity
import com.chase.passwordmaster.components.advancedrecyclerview.PackagedRecyclerViewAdapter
import com.chase.passwordmaster.components.blurringview.BlurringView
import com.chase.passwordmaster.data.AccountViewModel
import com.chase.passwordmaster.detail.DetailActivity
import com.chase.passwordmaster.detail.edit.EditActivity
import com.chase.passwordmaster.search.SearchActivity
import com.chase.passwordmaster.mine.MineActivity
import com.chase.passwordmaster.utils.vibrate
import com.chase.passwordmaster.utils.useDarkStatusBar
import com.chase.passwordmaster.utils.useImmersingNavigator
import com.mylhyl.circledialog.CircleDialog

class MainActivity : AppCompatActivity() {

    companion object {
        fun actionStart(context: Context, loginPassword: String) {
            val intent = Intent(context, MainActivity::class.java)
            intent.putExtra("loginPassword", loginPassword)
            context.startActivity(intent)
        }
    }

    private lateinit var accountViewModel: AccountViewModel

    private lateinit var rv: RecyclerView
    private lateinit var mainRVAdapter: MainRVAdapter
    private lateinit var ivAdd: ImageView
    private lateinit var cpSearch: ImageView
    private lateinit var cpMine: ImageView
    private lateinit var cpEmpty: ImageView
    private lateinit var cpBlur: BlurringView

    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        accountViewModel = ViewModelProviders.of(this).get(AccountViewModel::class.java)


        rv = findViewById(R.id.rv_main)
        ivAdd = findViewById(R.id.iv_add_main)
        cpSearch = findViewById(R.id.search_main)
        cpMine = findViewById(R.id.mine_main)
        cpEmpty = findViewById(R.id.empty_main)
        cpBlur = findViewById(R.id.blur_main)

        useDarkStatusBar()
        useImmersingNavigator(navigationBarColor = Color.WHITE)

        initRv()
        initIvAdd()
        initCPSearch()
        initCPMine()
        initCPEmpty()
        initCPBlur()

        accountViewModel.getAccountLiveData().observe(this, Observer {
//            mainRVAdapter.notifyDataSetChanged()
            rv.adapter?.notifyDataSetChanged()
            if (mainRVAdapter.accountList.isNotEmpty()) {
                cpEmpty.visibility = View.GONE
                rv.visibility = View.VISIBLE
            } else {
                cpEmpty.visibility = View.VISIBLE
                rv.visibility = View.GONE
            }
        })

    }

    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private fun initCPBlur() {
        cpBlur.setBlurredView(rv)
        cpBlur.invalidate()
    }

    private fun initCPEmpty() {
        if (mainRVAdapter.accountList.isEmpty()) {
            cpEmpty.visibility  = View.VISIBLE
        }
    }

    private fun initCPMine() {
        cpMine.setOnClickListener {
            MineActivity.actionStart(this)
        }
    }

    private fun initCPSearch() {
        cpSearch.setOnClickListener {
            SearchActivity.actionStart(this)
        }
    }

    private fun initIvAdd() {
        ivAdd.setOnClickListener {
            AddActivity.actionStart(this)
        }
    }

    private fun initRv() {
        rv.layoutManager = LinearLayoutManager(this)
        mainRVAdapter = MainRVAdapter(
            accountViewModel.getAccountLiveData().value ?: ArrayList(),
            MainRVAdapter.RInfo(
                rvLayout = R.layout.item_main_rv,
                tvWebsiteId = R.id.tv_website_item_main_rv,
                tvName = R.id.tv_name_item_main_rv,
                lName = R.id.layout_name_item_main_rv,
                tvUsernameId = R.id.tv_username_item_main_rv,
                tvWeChat = R.id.tv_weChat_item_main_rv,
                tvQQ = R.id.tv_qq_item_main_rv,
                tvEmail = R.id.tv_email_item_main_rv,
                tvTel = R.id.tv_phone_item_main_rv,
                lQQ = R.id.layout_qq_item_main_rv,
                lWeChat = R.id.layout_weChat_item_main_rv,
                lEmail = R.id.layout_email_item_main_rv,
                lTel = R.id.layout_phone_item_main_rv,
                blurLayout = R.id.blur_layout_item_rv,
                blur = R.id.blur_item_rv,
                delete = R.id.delete_item_rv,
                edit = R.id.edit_item_rv
            )
        )

        mainRVAdapter.itemClickListener = { holder: MainRVAdapter.VH, position: Int ->
            holder.itemView.setOnClickListener {
                Log.d("GSC:MainActivity", "itemClickListener called")
                DetailActivity.actionStart(this, position)
            }
        }

        mainRVAdapter.itemLongClickListener = { holder, position ->
            holder.itemView.setOnLongClickListener {
                // Vibrate
                vibrate()

                // 设置模糊遮罩
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    holder.cpBlur.setBlurredView(holder.itemView.findViewById(R.id.body_item_main_rv))
                    holder.cpBlur.invalidate()
                }
                // 显示遮罩
                showBlurCover(holder.cpBlurLayout)
                // 点击撤回遮罩
                holder.cpBlurLayout.setOnClickListener(::hideBlurCover)

                // 重绘导航栏模糊
                // 似乎没有用
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    cpBlur.setBlurredView(rv)
                    cpBlur.invalidate()
                }

                // 点击遮罩中的删除弹出删除对话框
                holder.cpDelete.setOnClickListener {
                    CircleDialog.Builder()
                        .setRadius(20)
                        .setWidth(0.8f)
                        .setTitle("删除账户")
                        .setText( "\n网站：${accountViewModel.getAccount(position)?.website}\n账号：${accountViewModel.getAccount(position)?.username}\n")
                        .setPositive("删除") {
                            accountViewModel.removeAccount(position)
                        }
                        .setNegative("取消", null)
                        .show(supportFragmentManager)
                }

                // 点击遮罩中的编辑进入编辑页面
                holder.cpEdit.setOnClickListener {
                    EditActivity.actionStart(this, position)
                }

                // LongClick的返回值为false表示只执行长按的事件
                // 为true表示执行完长按事件之后会执行点击事件OnClickListener
                false
                true
            }
        }

        rv.adapter = PackagedRecyclerViewAdapter<MainRVAdapter.VH>(
            mainRVAdapter,
            footer = LayoutInflater.from(this).inflate(R.layout.item_main_rv_footer, rv, false)
        )

        // 监听滚动事件，在滚动时渲染模糊
        rv.addOnScrollListener(object: RecyclerView.OnScrollListener() {
            @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                cpBlur.setBlurredView(recyclerView)
                cpBlur.invalidate()
            }
        })


    }

    // 显示模糊遮罩
    private fun showBlurCover(blurCover: View) {
        blurCover.visibility = View.VISIBLE
        blurCover.alpha = 1f
        val animation = AnimationUtils.loadAnimation(this, R.anim.alpha_show)
        blurCover.startAnimation(animation)
    }

    // 隐藏模糊遮罩
    private fun hideBlurCover(blurCover: View) {
        val animation = AnimationUtils.loadAnimation(this, R.anim.alpha_hide)
            .apply {
                setAnimationListener(object: Animation.AnimationListener {
                    override fun onAnimationRepeat(animation: Animation?) { }

                    override fun onAnimationStart(animation: Animation?) { }

                    override fun onAnimationEnd(animation: Animation?) {
                        blurCover.visibility = View.GONE
                    }

                })
            }
        blurCover.startAnimation(animation)
    }
}

